package xml;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import android.view.View;

import android.widget.RemoteViews;

import java.util.Calendar;

import oschina.by.isrefluxer.com.weatherapplication.BitmapsUtil;
import oschina.by.isrefluxer.com.weatherapplication.DateServer;
import oschina.by.isrefluxer.com.weatherapplication.R;
import oschina.by.isrefluxer.com.weatherapplication.Util;
import oschina.by.isrefluxer.com.weatherapplication.Weather;
import oschina.by.isrefluxer.com.weatherapplication.WeatherServer;

/**
 * Implementation of App Widget functionality.
 */
public class NewAppWidget extends AppWidgetProvider   {

    private static String deskclockPag = "com.android.deskclock";
    private static String weatherPag = "com.moji.aliyun";
    private static String calendatPag = "com.android.calendar";

    private static String uri = "content://com.yunos.weather.provider/location";

    public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int[] appWidgetIds) {
        for (int appWidgetId : appWidgetIds) {
            bindClickEvent(context);
        }
        updateTimeWidget(context,appWidgetManager,
                appWidgetIds);

        updateWeatherWidget(context,appWidgetManager,
                appWidgetIds);

    }

   public static void updateWeatherWidget(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        for (int appWidgetId : appWidgetIds) {
            Weather weather = getCurrentWeather(context);

            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
            updateWeather(views,context,weather);
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }

    public static void updateTimeWidget(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        for (int appWidgetId : appWidgetIds) {
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
            updateTime(views,context);
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }

    /**
     * bindClickevent start timeclcokActivity calendarActivity mojiActivity
     * @author zhangbi
     * @param context
     */
    private static void bindClickEvent(Context context) {

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
        views.setOnClickPendingIntent(R.id.timeclock,getPendingIntent(context,deskclockPag));
        views.setOnClickPendingIntent(R.id.birdweather,getPendingIntent(context,weatherPag));
        views.setOnClickPendingIntent(R.id.current_date,getPendingIntent(context,calendatPag));

    }

    /**
     * return pagname for Intent
     * @author zhangbi
     * @param context
     * @param Pag
     * @return
     */
    private static PendingIntent getPendingIntent(Context context, String Pag) {

        return PendingIntent
                .getActivity(context, 0, context.getPackageManager().getLaunchIntentForPackage(Pag), 0);

    }

    private static void updateWeather(RemoteViews views, Context context,Weather weather) {
        if(BitmapsUtil.getemperBitmaps().size()==0)
        {
            BitmapsUtil.startTemperBitmaps(context);
        }
        if(BitmapsUtil.getemperBitmaps().size()>0)
        {
            if(weather.getCurrent_temperature().contains("-"))
            {
                views.setImageViewBitmap(R.id.fushu,BitmapsUtil.getemperBitmaps().get(12));
                views.setViewVisibility(R.id.fushu,View.VISIBLE);
                int tem = Integer.parseInt(weather.getCurrent_temperature().replace("-",""));
                if(tem/10>0)
                {
                    views.setImageViewBitmap(R.id.ten_current_temperature,BitmapsUtil.getemperBitmaps().get(tem/10));
                    views.setViewVisibility(R.id.ten_current_temperature, View.VISIBLE);
                }
                views.setImageViewBitmap(R.id.one_current_temperature,BitmapsUtil.getemperBitmaps().get(tem%10));
            }else{
               int tem = Integer.parseInt(weather.getCurrent_temperature());
                if(tem/10>0)
                {
                    views.setImageViewBitmap(R.id.ten_current_temperature,BitmapsUtil.getemperBitmaps().get(tem/10));
                    views.setViewVisibility(R.id.ten_current_temperature, View.VISIBLE);
                }
                views.setImageViewBitmap(R.id.one_current_temperature,BitmapsUtil.getemperBitmaps().get(tem%10));
            }
            views.setImageViewBitmap(R.id.current_temperatureF,BitmapsUtil.getemperBitmaps().get(10));

            if (weather.getMin_temperature().contains("-"))
            {
                views.setImageViewBitmap(R.id.minfushu,BitmapsUtil.getemperBitmaps().get(12));
                views.setViewVisibility(R.id.minfushu,View.VISIBLE);
                int tem = Integer.parseInt(weather.getMin_temperature().replace("-",""));
                if(tem/10>0)
                {
                    views.setImageViewBitmap(R.id.minten_current_temperature,BitmapsUtil.getemperBitmaps().get(tem/10));
                    views.setViewVisibility(R.id.minten_current_temperature, View.VISIBLE);
                }
                views.setImageViewBitmap(R.id.minone_current_temperature,BitmapsUtil.getemperBitmaps().get(tem%10));
            }else{
                int tem = Integer.parseInt(weather.getMin_temperature());
                if(tem/10>0)
                {
                    views.setImageViewBitmap(R.id.minten_current_temperature,BitmapsUtil.getemperBitmaps().get(tem/10));
                    views.setViewVisibility(R.id.minten_current_temperature, View.VISIBLE);
                }
                views.setImageViewBitmap(R.id.minone_current_temperature,BitmapsUtil.getemperBitmaps().get(tem%10));
            }
            views.setImageViewBitmap(R.id.mincurrent_temperatureF,BitmapsUtil.getemperBitmaps().get(10));

            if (weather.getMax_temperature().contains("-"))
            {
                views.setImageViewBitmap(R.id.maxfushu,BitmapsUtil.getemperBitmaps().get(12));
                views.setViewVisibility(R.id.maxfushu,View.VISIBLE);
                int tem = Integer.parseInt(weather.getMax_temperature().replace("-",""));
                if(tem/10>0)
                {
                    views.setImageViewBitmap(R.id.maxten_current_temperature,BitmapsUtil.getemperBitmaps().get(tem/10));
                    views.setViewVisibility(R.id.maxten_current_temperature, View.VISIBLE);
                }
                views.setImageViewBitmap(R.id.maxone_current_temperature,BitmapsUtil.getemperBitmaps().get(tem%10));
            }else{
                int tem = Integer.parseInt(weather.getMax_temperature());
                if(tem/10>0)
                {
                    views.setImageViewBitmap(R.id.maxten_current_temperature,BitmapsUtil.getemperBitmaps().get(tem/10));
                    views.setViewVisibility(R.id.maxten_current_temperature, View.VISIBLE);
                }
                views.setImageViewBitmap(R.id.maxone_current_temperature,BitmapsUtil.getemperBitmaps().get(tem%10));
            }
            views.setImageViewBitmap(R.id.maxcurrent_temperatureF,BitmapsUtil.getemperBitmaps().get(10));

        }

        views.setTextViewText(R.id.city,weather.getCity());
        views.setImageViewResource(R.id.current_condition,weather.current_conditionRes(context));



    }

    private static void updateTime(RemoteViews views,Context context) {

            Calendar cl = Calendar.getInstance();
          //  int s = cl.get(Calendar.SECOND);
            int m = cl.get(Calendar.MINUTE);
            int h = cl.get(Calendar.HOUR);
            int day = cl.get(Calendar.DAY_OF_MONTH);
            int month = cl.get(Calendar.MONTH);
            int apm = cl.get(Calendar.AM_PM);


         if(apm==1){
            if(Util.getTIME_12_24(context).equals("24"))
            {
                h+=12;
            }
           }
            if(BitmapsUtil.getBitmaps().size()==0)
            {
                BitmapsUtil.start(context);
            }
        if(BitmapsUtil.getBitmaps().size()!=0) {
            views.setImageViewBitmap(R.id.tenHour, BitmapsUtil.getBitmaps().get(h / 10));
            views.setImageViewBitmap(R.id.oneHour, BitmapsUtil.getBitmaps().get(h % 10));
            views.setImageViewResource(R.id.point, R.drawable.point);
            views.setImageViewBitmap(R.id.tenMin, BitmapsUtil.getBitmaps().get(m / 10));
            views.setImageViewBitmap(R.id.oneMin, BitmapsUtil.getBitmaps().get(m % 10));
        }
        views.setTextViewText(R.id.current_date,month+"月"+day+"日");

    }

    private static Weather getCurrentWeather(Context context) {
        Cursor cursor = context.getContentResolver().query(Uri.parse(uri), null, null, null,null);
        Weather weather = new Weather();
        if(cursor.moveToFirst()) {
            Log.i("ContentTest", "current_condition_code="+ cursor.getInt(0)+ "," +
                    "current_temperature="+ cursor.getString(cursor.getColumnIndex("current_temperature"))+ ","+
                    "city = "+cursor.getString(cursor.getColumnIndex("city"))+ ","+
                    "current_condition = "+cursor.getString(cursor.getColumnIndex("current_condition"))+","+
                    "current_condition_code = "+cursor.getInt(cursor.getColumnIndex("current_condition_code")));
            weather.setMax_temperature(cursor.getString(cursor.getColumnIndex("max_temperature")));
            weather.setMin_temperature(cursor.getString(cursor.getColumnIndex("min_temperature")));
            weather.setCity(cursor.getString(cursor.getColumnIndex("city")));
            weather.setCurrent_condition(cursor.getString(cursor.getColumnIndex("current_condition")));
            weather.setCurrent_condition_code(cursor.getInt(cursor.getColumnIndex("current_condition_code")));
            weather.setCurrent_temperature(cursor.getString(cursor.getColumnIndex("current_temperature")));

        }
        return weather;


    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them

            updateAppWidget(context, appWidgetManager, appWidgetIds);
            context.startService(new Intent(context, WeatherServer.class));
            context.startService(new Intent(context, DateServer.class));

    }

    @Override
    public void onEnabled(Context context) {
        // Enter relevant functionality for when the first widget is created
//        context.startService(new Intent(context, WeatherServer.class));
//        context.startService(new Intent(context, DateServer.class));
    }

    @Override
    public void onDisabled(Context context) {
        // Enter relevant functionality for when the last widget is disabled
        context.stopService(new Intent(context, WeatherServer.class));
        context.stopService(new Intent(context, DateServer.class));
    }
}

